# -*- coding: utf-8 -*-
def login():
    response.flash = T("Welcome to PyCube")
    # session.policy_model_dict = {}
    if request.vars.username and request.vars.password:
        db.auth_user.password.requires = CRYPT(key=auth.settings.hmac_key, min_length=0)
        if auth.login_bare(username=request.vars.username,password=request.vars.password):
            session.authorized = True
            session.last_time = t0
            redirect(URL('pages', 'index',args=request.args))
        else:
            response.flash = T('User name or password error！')
    elif request.vars:
        response.flash = T('User name or password is empty！')
    session.counter = (session.counter or 0) + 1
    return dict(message="login", counter=session.counter)

def logout():
    auth.logout_bare()
    redirect(URL('pages','login'))

#@cache(request.env.path_info, time_expire=auth.settings.expiration, cache_model=cache.ram)
def index():
    #response.flash = T("Welcome to PyCube")
    menu = cache.ram(session.auth.user.id, lambda: getMenuRoot(), time_expire=1)
    return dict(message='index logo',auth=session.auth,menu=menu)

def getMenuRoot():
    if(session.auth.user.username=='admin'):
        menuRows = db(db.sys_menu.is_show == True).select(orderby=db.sys_menu.sortno)  # 全部权限  后续根据管理员权限判断,暂时直接admin判断
    else:
        menuRows= db( (db.sys_role_menu.group_id.belongs(session.auth.user_groups.keys())) & (db.sys_menu.is_show ==True) ).select(
                   db.sys_menu.ALL,distinct=True,orderby=db.sys_menu.sortno,
                   left=db.sys_role_menu.on(db.sys_role_menu.menu_id == db.sys_menu.id))

    menu=UL(LI(T('Main Nav'),_class='header'),_class='sidebar-menu')
    #db((db.sys_menu.parent_id == None) & (db.sys_menu.is_show ==True)).select(orderby=db.sys_menu.sortno)
    for parent in menuRows.find(lambda row: row.parent_id == None):
        menu.append(getMenuContent(getMenuChild(parent,menuRows),parent))
    return menu

def getMenuChild(parent,rows):
    ul=UL(_class='treeview-menu')
    #db((db.sys_menu.parent_id == parent.id) & (db.sys_menu.is_show ==True )).select(orderby=db.sys_menu.sortno)
    for child in  rows.find(lambda row: row.parent_id == str(parent.id)):
        ul.append(getMenuContent(getMenuChild(child,rows),child))
    return ul

def getMenuContent(content,child):
    list=['bg-red', 'bg-yellow', 'bg-aqua', 'bg-blue', 'bg-light-blue', 'bg-green', 'bg-navy', 'bg-teal', 'bg-olive',
          'bg-lime', 'bg-orange', 'bg-fuchsia', 'bg-purple', 'bg-maroon', 'bg-black']
    from random import choice
    return LI(A(I(_class='fa ' + (child.icon == '' and 'fa-circle-o '+choice(list).replace('bg','text') or child.icon)),
              SPAN(child.name),
              content.__len__() != 0 and SPAN(I(_class='fa fa-angle-left pull-right'),TAG.small( content.__len__() , _class='label pull-right '+choice(list) ), _class='pull-right-container') or '',
              _href=(child.href == '' and 'javascript:void(0);' or '/' + request.application + child.href),
               **{child.href == '' and ' ' or '_target':child.target }
                ), content.__len__() != 0 and content or '')

def change_password():
    form = auth.change_password(next=URL('pages', 'index'))
    return dict(form=form)

def hello():
    session.flash = T("Hello World")
    return 'hello world'

def menu():
    return dict(form=LOAD( 'pages' , 'menuc.load'))

def menuc():
    grid = SQLFORM.grid(db.sys_menu,paginate=10,searchable=False,csv=False)
    return dict(grid=grid)

def user():
    return dict(form=LOAD('pages', 'userc.load'))

def userc():
    grid = SQLFORM.grid(db.auth_user,paginate=10,searchable=False,csv=False)
    return dict(grid=grid)

def role():
    return dict(form=LOAD('pages', 'rolec.load'))

def rolec():
    grid = SQLFORM.grid(db.auth_group,paginate=10,searchable=False,csv=False)
    return dict(grid=grid)

def membership():
    return dict(form=LOAD('pages', 'membershipc.load'))

def membershipc():
    grid = SQLFORM.grid(db.auth_membership,paginate=10,searchable=False,csv=False)
    return dict(grid=grid)

def rolemenu():
    return dict(form=LOAD('pages', 'rolemenuc.load'))

def rolemenuc():
    grid = SQLFORM.grid(db.sys_role_menu,paginate=10,searchable=False,csv=False)
    return dict(grid=grid)

def sysdict():
    return dict(form=LOAD('pages', 'sysdictc.load'))

def sysdictc():
    grid = SQLFORM.grid(db.sys_dict,paginate=10,searchable=False,csv=False)
    return dict(grid=grid)